package com.xsherl.leetcode.solution;

import cn.hutool.core.lang.Assert;

public class SearchInsertPosition {

    /**
     * 二分查找法，如果没有查找到目标值，该目标值应该在left位置
     */
    public int searchInsert(int[] nums, int target) {
        int len = nums.length, left = 0, right = len - 1;
        while (left <= right){
            int mid = (left + right) / 2;
            int val = nums[mid];
            if (val < target){
                left = mid + 1;
            } else if (val > target){
                right = mid - 1;
            } else {
                return mid;
            }
        }
        return left;
    }

    public static void main(String[] args) {
        int[] nums = {1,3,5,6};
        int i = new SearchInsertPosition().searchInsert(nums, 5);
        System.out.println(i);
        Assert.isTrue(i == 2);
        int i1 = new SearchInsertPosition().searchInsert(nums, 2);
        System.out.println(i1);
        Assert.isTrue(i1 == 1);
        int i2 = new SearchInsertPosition().searchInsert(nums, 7);
        System.out.println(i2);
        Assert.isTrue(i2 == 4);
        int i3 = new SearchInsertPosition().searchInsert(nums, 0);
        System.out.println(i3);
        Assert.isTrue(i3 == 0);
    }

}
